<template>
  <div class="tools-container">
    <Sidebar 
      title="辅助工具" 
      :items="sidebarItems" 
      :current-type="activeTool"
      @select="handleToolSelect"
    />

    <main class="tools-main">
      <div class="tool-header">
        <h2>{{ currentToolName }}</h2>
        <p class="tool-desc">{{ currentToolDesc }}</p>
      </div>

      <div class="tool-content">
        <!-- Timestamp Converter -->
        <div v-if="activeTool === 'timestamp'" class="tool-panel">
          <div class="input-group">
            <label>当前时间戳 (秒)</label>
            <div class="row">
              <input v-model="tsInput" type="text" placeholder="Unix Timestamp" />
              <button class="btn-primary" @click="convertTs">转换</button>
              <button class="btn-secondary" @click="tsInput = Math.floor(Date.now() / 1000)">获取当前</button>
            </div>
            <div class="result-box" v-if="tsResult">
              {{ tsResult }}
            </div>
          </div>
          
          <div class="divider"></div>

          <div class="input-group">
            <label>日期时间</label>
            <div class="row">
              <input v-model="dateInput" type="text" placeholder="YYYY-MM-DD HH:mm:ss" />
              <button class="btn-primary" @click="convertDate">转换</button>
              <button class="btn-secondary" @click="dateInput = formatDate(new Date())">获取当前</button>
            </div>
            <div class="result-box" v-if="dateResult">
              {{ dateResult }}
            </div>
          </div>
        </div>

        <!-- Hash Calculator -->
        <div v-if="activeTool === 'hash'" class="tool-panel">
          <div class="input-group">
            <label>输入文本</label>
            <textarea v-model="hashInput" rows="4" placeholder="请输入要计算的文本..."></textarea>
          </div>
          
          <div class="hash-results">
            <div class="hash-row">
              <span class="label">MD5</span>
              <input :value="md5Result" readonly />
              <button class="btn-copy" @click="copyText(md5Result)">复制</button>
            </div>
            <div class="hash-row">
              <span class="label">SHA1</span>
              <input :value="sha1Result" readonly />
              <button class="btn-copy" @click="copyText(sha1Result)">复制</button>
            </div>
            <div class="hash-row">
              <span class="label">SHA256</span>
              <input :value="sha256Result" readonly />
              <button class="btn-copy" @click="copyText(sha256Result)">复制</button>
            </div>
          </div>
        </div>

        <!-- Base64 -->
        <div v-if="activeTool === 'base64'" class="tool-panel">
          <div class="split-view">
            <div class="half">
              <label>原文 (Text)</label>
              <textarea v-model="base64Text" rows="10" placeholder="输入文本..."></textarea>
            </div>
            <div class="actions">
              <button class="btn-primary" @click="toBase64">编码 &gt;&gt;</button>
              <button class="btn-primary" @click="fromBase64">&lt;&lt; 解码</button>
            </div>
            <div class="half">
              <label>Base64</label>
              <textarea v-model="base64Code" rows="10" placeholder="Base64 编码..."></textarea>
            </div>
          </div>
        </div>
      </div>
    </main>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import Sidebar from '@/components/Sidebar.vue'
import CryptoJS from 'crypto-js' // We need to ensure crypto-js is installed or use Web Crypto API

const activeTool = ref('timestamp')

const sidebarItems = [
  { type: 'timestamp', label: '时间戳转换', icon: '⏰' },
  { type: 'hash', label: 'Hash计算', icon: '🔒' },
  { type: 'base64', label: 'Base64编解码', icon: '🔤' }
]

const currentToolName = computed(() => {
  const item = sidebarItems.find(i => i.type === activeTool.value)
  return item ? item.label : ''
})

const currentToolDesc = computed(() => {
  const map = {
    timestamp: 'Unix时间戳与日期时间相互转换',
    hash: '计算文本的 MD5, SHA1, SHA256 哈希值',
    base64: 'Base64 编码与解码工具'
  }
  return map[activeTool.value] || ''
})

const handleToolSelect = (type) => {
  activeTool.value = type
}

// Timestamp Logic
const tsInput = ref(Math.floor(Date.now() / 1000))
const tsResult = ref('')
const dateInput = ref(formatDate(new Date()))
const dateResult = ref('')

function formatDate(date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const min = String(date.getMinutes()).padStart(2, '0')
  const s = String(date.getSeconds()).padStart(2, '0')
  return `${y}-${m}-${d} ${h}:${min}:${s}`
}

const convertTs = () => {
  const ts = parseInt(tsInput.value)
  if (isNaN(ts)) {
    tsResult.value = '无效的时间戳'
    return
  }
  // Check if ms or s
  const date = new Date(ts.toString().length > 10 ? ts : ts * 1000)
  tsResult.value = formatDate(date)
}

const convertDate = () => {
  const date = new Date(dateInput.value)
  if (isNaN(date.getTime())) {
    dateResult.value = '无效的日期格式'
    return
  }
  dateResult.value = Math.floor(date.getTime() / 1000).toString()
}

// Hash Logic
const hashInput = ref('')
const md5Result = computed(() => hashInput.value ? CryptoJS.MD5(hashInput.value).toString() : '')
const sha1Result = computed(() => hashInput.value ? CryptoJS.SHA1(hashInput.value).toString() : '')
const sha256Result = computed(() => hashInput.value ? CryptoJS.SHA256(hashInput.value).toString() : '')

// Base64 Logic
const base64Text = ref('')
const base64Code = ref('')

const toBase64 = () => {
  try {
    const words = CryptoJS.enc.Utf8.parse(base64Text.value)
    base64Code.value = CryptoJS.enc.Base64.stringify(words)
  } catch (e) {
    alert('编码失败')
  }
}

const fromBase64 = () => {
  try {
    const words = CryptoJS.enc.Base64.parse(base64Code.value)
    base64Text.value = CryptoJS.enc.Utf8.stringify(words)
  } catch (e) {
    alert('解码失败: 无效的Base64字符串')
  }
}

const copyText = (text) => {
  if (!text) return
  navigator.clipboard.writeText(text)
}
</script>

<style scoped>
.tools-container {
  display: flex;
  height: 100%;
  background: #f5f7fa;
}

.tools-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.tool-header {
  padding: 20px 30px;
  background: white;
  border-bottom: 1px solid #e6e6e6;
}

.tool-header h2 {
  margin: 0 0 5px 0;
  color: #303133;
}

.tool-desc {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.tool-content {
  flex: 1;
  padding: 30px;
  overflow-y: auto;
}

.tool-panel {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  max-width: 800px;
  margin: 0 auto;
}

.input-group {
  margin-bottom: 20px;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  color: #606266;
  font-weight: 500;
}

.row {
  display: flex;
  gap: 10px;
}

input[type="text"], textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

input[type="text"] {
  flex: 1;
}

.result-box {
  margin-top: 10px;
  padding: 10px;
  background: #f0f9eb;
  color: #67c23a;
  border-radius: 4px;
  font-family: monospace;
}

.divider {
  height: 1px;
  background: #ebeef5;
  margin: 30px 0;
}

.hash-row {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 10px;
}

.hash-row .label {
  width: 80px;
  font-weight: bold;
  color: #606266;
}

.hash-row input {
  flex: 1;
  background: #f5f7fa;
  font-family: monospace;
}

.split-view {
  display: flex;
  gap: 20px;
  align-items: center;
}

.half {
  flex: 1;
}

.actions {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.btn-primary {
  background: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-copy {
  background: white;
  border: 1px solid #dcdfe6;
  color: #606266;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-copy:hover {
  color: #409eff;
  border-color: #c6e2ff;
}
</style>
